<script>
import { atLeast } from '@/utils/kris_utils'
import { getDormitory } from '@/api/basic'
import { editRoom } from '@/api/dorm'
import { editPersonForRoom } from '@/api/v2/dorm'
import { getAllUser } from '@/api/personnel'
import RoomForm from '../RoomForm/RoomForm.vue'
import DialogContent from '@/components/DialogContent/index.vue'
export default {
  components: {
    RoomForm,
    DialogContent
  },
  props: {
    value: {
      type: Boolean,
      required: true,
      default: false
    },
    room: {
      required: true,
      default() {
        return {
          apartmentID: null,
          id: null,
          roomName: '',
          bad: 1,
          rent: 0,
          employees: [],
          photos: []
        }
      }
    },
    userNumber: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      apartments: [],
      employeeInfo: [],
      form: {
        apartmentID: null,
        roomName: '',
        bad: 1,
        rent: 0,
        remark: '',
        employees: [],
        photos: []
      },
      isSubmitting: false,
      // KRIS:TEMP
      urls: [],
      userList: [],
      updateUserRoom: {}
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.value
      },
      set(visible) {
        this.$emit('input', visible)
      }
    },
    isActionDisabled() {
      return this.isSubmitting
    },
    isShow() {
      return this.dialogVisible && atLeast(this.room, ['apartmentID', 'id', 'roomName', 'bad', 'rent', 'photos'])
    },
    apartmentOptions() {
      return this.apartments.map(apartment => {
        const { address, id } = apartment
        return {
          label: address,
          value: id
        }
      })
    },
    userOptions() {
      return this.employeeInfo.map(employee => {
        const { username, id } = employee
        return {
          label: username,
          value: id
        }
      })
    }
  },
  watch: {
    isShow(visible) {
      if (!visible) return
      this.form = { ...this.room }
      this.urls = this.room.photos ?? []
    }
  },
  created() {
    this.initData()
    this.getEmployessList()
  },
  mounted() {
    // console.log(this.userOptions,'-----userOptions');
  },
  methods: {
    sleep(t) {
      return new Promise(r => setTimeout(r, t))
    },
    handleClose() {
      if (this.isActionDisabled) return
      this.dialogVisible = false
    },
    // 获取宿舍信息
    async getApartments() {
      const result = await getDormitory()
      this.apartments = result?.data ?? []
      console.log(result, '宿舍信息')
    },
    // 获取员工信息
    async getEmployessList() {
      try {
        const res = await getAllUser({ job_status: 1 })
        this.employeeInfo = res?.data ?? []
        console.log(this.userOptions, '-----userOptions')
      } catch (error) {
        this.$message.error('获取员工信息失败')
        console.log('error ------>', error)
      }
    },
    async handleConfirm() {
      try {
        const flag = await this.$refs.form?.validate()
        if (!flag) return

        this.isSubmitting = true
        await this.sleep(300)

        const params = this.buildParams()
        console.log(params, 'params')
        if (params.number < this.userNumber) {
          this.isSubmitting = false
          return this.$message.error(`修改房间数不能小于当前入住人员数量,当前入住人员${this.userNumber}`)
        }
        const result = await editRoom(params)
        try {
          // const userResult = await editPersonForRoom(this.updateUserRoom)
          console.log(this.updateUserRoom)
        } catch (error) {
          console.log(error)
        }

        // const updateUser=await editPersonForRoom();
        if (result.code !== 201) { throw new Error(result?.data?.message ?? '修改失败') }

        this.isSubmitting = false
        this.$emit('success', result)
        this.$refs.form?.resetFields()
      } catch (e) {
        this.isSubmitting = false
        this.$emit('failed', e)
      }
    },
    buildParams() {
      const {
        roomName,
        apartmentID,
        bad,
        rent,
        remark,
        photos
      } = this.form

      const params = {
        id: this.room.id,
        dormitory_id: apartmentID,
        name: roomName,
        number: bad / 1,
        rent: rent / 1,
        remark: remark,
        photo: JSON.stringify(photos)
      }

      return params
    },
    async loadData() {
      const result = await Promise.allSettled([
        this.getApartments()
      ])

      const failTasks = result.filter(item => item.status === 'rejected')
      if (failTasks.length <= 0) return
      throw failTasks.at(0)
    },
    async initData() {
      try {
        await this.loadData()
      } catch (e) {
        console.log(e)
      }
    },
    handleSelectChange(newList) {
      this.userList = newList
        .filter(item => !isNaN(item.user.username))
        .map(item => ({ old_user_id: item.user.id, new_user_id: parseInt(item.user.username) }))
      // this.updateUserRoom={...this.userList,...this.room.id}
      const [user, { id: room_id }] = [this.userList[0], this.room]
      this.updateUserRoom = { ...user, room_id }
    }
  }
}
</script>

<template>
  <div class="create-apartment">
    <DialogContent
      title="编辑房间"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <RoomForm
        ref="form"
        v-model="form"
        :urls="urls"
        :room-user="getEmployessList"
        :user-options="userOptions"
        :apartment-options="apartmentOptions"
        :fetch-apartments="getApartments"
        @select-change="handleSelectChange"
      />
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="isSubmitting" @click="handleClose">取 消</el-button>
        <el-button type="primary" :loading="isSubmitting" :disabled="isSubmitting" @click="handleConfirm">确 定</el-button>
      </div>
    </DialogContent>
    <el-dialog />
  </div>
</template>

<style lang="scss"></style>
